<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/29
 * Time: 16:15
 */

namespace app\index\server;


use app\index\model\Card as CardModel;
use app\lib\exception\DatabaseException;
use think\Exception;

class CardServer extends BaseServer
{
    public function getList($params = [])
    {
        $params = $this->prep_param($params);
        try {
            // 总条数
            $count = CardModel::count();
            $list = CardModel::order($params['sort'], $params['order'])
                ->limit($params['offset'], $params['limit'])
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function addOrUpdate($params = [])
    {
        // 准备数组
        $prep_data = [
            'type' => $params['type'],
            'bank_name' => $params['bank_name'],
            'branch_name' => $params['branch_name'],
            'card_number' => $params['card_number'],
            'surename' => $params['surename'],
            'balance' => $params['balance'],
            'status' => $params['status']
        ];
        try {
            if(isset($params['primary_key'])) {
                // 更新
                $result = CardModel::where('id', $params['primary_key'])
                    ->update($prep_data);
            } else {
                $result = CardModel::insert($prep_data);
            }
            if(!$result) {
                return setMsg(0, '操作银行卡失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '操作银行卡成功');
    }

    public function detail($id)
    {
        try {
            $info = CardModel::where('id', $id)
                ->find();
            if(!$info) {
                return setMsg(0, '操作银行卡失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, 'OK', $info);
    }

    public function changeStatus($id)
    {
        try {
            $info = CardModel::where('id', $id)
                ->find();
            $info->status = abs(($info->status) - 1);
            $result = $info->save();
            if(!$result) {
                return setMsg(0, '修改此分类状态失败');
            }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改此分类 状态成功');
    }
}